package com.spark.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spark.basecommon.entity.user.UmsAdmin;
import com.spark.basecommon.entity.user.UmsPermission;
import com.spark.basecommon.entity.user.UmsRole;
import com.spark.basecommon.entity.vo.LoginUserVO;
import com.spark.basecommon.exception.BusinessException;
import com.spark.basecommon.utils.QueryUtil;
import com.spark.userservice.mapper.UmsAdminMapper;
import com.spark.userservice.service.IUmsAdminService;
import com.spark.userservice.service.IUmsPermissionService;
import com.spark.userservice.service.IUmsRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author fuqiang
 * @since 2020-09-28
 */
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements IUmsAdminService {

    @Autowired
    private IUmsRoleService iUmsRoleService;
    @Autowired
    private IUmsPermissionService umsPermissionService;

    @Override
    public String login(String username, String password) {

        return null;
    }

    @Override
    public LoginUserVO getUserInfoByUserName(String username) {
        // 查询用户信息
        LambdaQueryWrapper<UmsAdmin> eq = QueryUtil.getQueryBean(UmsAdmin.class).eq(UmsAdmin::getUsername,username);
        UmsAdmin admin = this.getOne(eq);
        if(null == admin){
            throw new BusinessException("根据 "+username+" 没有查询到用户信息");
        }
        // 构造登录bean userdetails
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(admin,loginUserVO);

        // 根据用户查询角色信息
        Set<UmsRole> roles = iUmsRoleService.findRolesByUserId(admin.getId());
        loginUserVO.setSysRoles(roles);
        if(CollectionUtils.isEmpty(roles)){
            return loginUserVO;
        }

        // 查询用户权限信息
        List<Long> roleIds = roles.parallelStream().map(r -> r.getId()).collect(Collectors.toList());
        Set<UmsPermission> permissionSet = umsPermissionService.findPermissionByRoleIds(roleIds);

        if(CollectionUtils.isEmpty(permissionSet)){
            return loginUserVO;
        }
        Set<String> permissions = permissionSet.parallelStream()
                                    .filter(p -> null != p.getValue())
                                    .map(p -> p.getValue())
                                    .collect(Collectors.toSet());
        loginUserVO.setPermissions(permissions);

        return loginUserVO;
    }

}
